package interview.bytedance;

import lombok.SneakyThrows;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ThreadPoolDemo
 *
 * @author <a href="zhaoyingling12@163.com">Zhao Simon</a>
 * @description:
 * @date 2022/3/21
 **/
public class ThreadPoolDemo {


    public static void main(String[] args) throws InterruptedException {
        AtomicInteger atomicInteger = new AtomicInteger(1);
        ReentrantLock lock = new ReentrantLock();

        ExecutorService service = Executors.newFixedThreadPool(30);
        for (int i = 0; i < 30; i++) {
            service.execute(new PrintTask(atomicInteger, lock));
        }
    }

    static class PrintTask implements Runnable {

        private final AtomicInteger atomicInteger;

        private ReentrantLock lock;


        public PrintTask(AtomicInteger atomicInteger, ReentrantLock lock) {
            this.atomicInteger = atomicInteger;
            this.lock = lock;
        }

        @Override
        public void run() {
            lock.lock();
            try {
                if (atomicInteger.get() % 3 == 1) {
                    // 打印a
                    System.out.println(Thread.currentThread().getName() + "打印A");
                    atomicInteger.incrementAndGet();
                } else if (atomicInteger.get() % 3 == 2) {
                    // 打印b
                    System.out.println(Thread.currentThread().getName() + "打印B");
                    atomicInteger.incrementAndGet();
                } else if (atomicInteger.get() % 3 == 0) {
                    // 打印C
                    System.out.println(Thread.currentThread().getName() + "打印C");
                    atomicInteger.incrementAndGet();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}
